package com.beta.cust.bind.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beta.cust.bind.api.request.CustListReq;
import com.beta.cust.bind.api.response.CustDetailResp;
import com.beta.cust.bind.constant.BusinessConstant;
import com.beta.cust.bind.mapper.CustInfoMapper;
import com.beta.cust.bind.mapper.entity.CustInfo;
import com.beta.cust.bind.service.ICustInfoService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 客户信息表 服务实现类
 * </p>
 *
 * @author pcc
 * @since 2024-03-12
 */
@Service
public class CustInfoServiceImpl extends ServiceImpl<CustInfoMapper, CustInfo> implements ICustInfoService {

    @Resource
    private CustInfoMapper custInfoMapper;

    @Override
    public CustDetailResp selectByUserAndExternalId(String userId, String externalUserId, String corpId) {
        if (ObjectUtils.allNull(userId, externalUserId)) {
            return null;
        }
        return custInfoMapper.selectByUserAndExternalId(userId, externalUserId, corpId);
    }

    @Override
    public IPage<CustDetailResp> selectPage(CustListReq req) {
        Page<CustDetailResp> page = new Page<>(req.getCurrentPage(), req.getPageSize());
        QueryWrapper<CustInfo> wapper = new QueryWrapper<CustInfo>();
        wapper.eq("re.user_id", req.getUserId());
        wapper.eq(null != req.getCorpId(),"re.corp_id", req.getCorpId());
        wapper.eq("re.del_flag", BusinessConstant.IS_NOT_DEL_FLAG);
        wapper.eq("info.del_flag", BusinessConstant.IS_NOT_DEL_FLAG);
        wapper.eq(null != req.getCertified(), "info.certified", req.getCertified());
        if (StringUtils.isNotEmpty(req.getSearchParam())) {
            wapper.and(qw -> qw.or(q1->q1.like("crm.name", req.getSearchParam()).eq("info.certified",BusinessConstant.IS_CERTIFICATED))
                    .or(q2->q2.like("crm.phone", req.getSearchParam()).eq("re.certified",BusinessConstant.IS_CERTIFICATED))
                    .or(q3->q3.like("info.name", req.getSearchParam()).eq("info.certified",BusinessConstant.NOT_CERTIFICATED)));
        }
        if (null == req.getCertified()) {
            wapper.orderByDesc("info.certified")
                    .orderByDesc("re.certified")
                    .orderByDesc("crm.total_asset")
                    .orderByAsc("crm.name_first_pinyin")
                    .orderByDesc("re.id");
        } else if (req.getCertified() == BusinessConstant.IS_CERTIFICATED) {
            //先排归属自己名下的客户，按客户总资产倒序的顺序排列，总资产一致的，按姓名首字母A-Z顺序排列,再排非自己所属的客户，按添加的时间倒序
            wapper.orderByDesc("re.certified")
                    .orderByDesc("crm.total_asset")
                    .orderByAsc("crm.name_first_pinyin")
                    .orderByDesc("re.id");
        }else if(req.getCertified() == BusinessConstant.NOT_CERTIFICATED){
            wapper.orderByDesc("re.id");
        }
        return custInfoMapper.listPage(page, wapper);
    }

    @Override
    public CustDetailResp getLatest(String userId, String corpId) {
        Page<CustDetailResp> page = new Page<>(1, 1);
        QueryWrapper<CustInfo> wapper = new QueryWrapper<CustInfo>();
        wapper.eq("re.user_id", userId);
        wapper.eq(null != corpId,"re.corp_id", corpId);
        wapper.eq("re.del_flag", BusinessConstant.IS_NOT_DEL_FLAG);
        wapper.eq("info.del_flag", BusinessConstant.IS_NOT_DEL_FLAG);
        IPage<CustDetailResp> resultPage = custInfoMapper.getLatestPage(page, wapper);
        return resultPage.getTotal() > 0 ? resultPage.getRecords().get(0) : null;
    }

    @Override
    public boolean updateByExternal(String externalUserId, CustInfo custInfo, String corpId) {
        if (StringUtils.isEmpty(externalUserId) || null == custInfo) {
            return false;
        }
        Integer result = this.custInfoMapper.update(custInfo, new LambdaQueryWrapper<CustInfo>()
                .eq(CustInfo::getDelFlag, BusinessConstant.IS_NOT_DEL_FLAG)
                .eq(null != corpId,CustInfo::getCorpId, corpId)
                .eq(CustInfo::getExternalUserid, externalUserId));
        return result > 0;
    }
}
